package com.simpleim.starter.processor;

import com.simpleim.common.ProtoInstant;
import com.simpleim.im.common.bean.User;
import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.protoBuilder.LoginResponceBuilder;
import com.simpleim.starter.server.ServerSession;
import com.simpleim.starter.server.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginProcesser extends AbstractServerProcesser {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginProcesser.class);

    @Autowired
    private LoginResponceBuilder loginResponceBuilder;

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.LOGIN_REQUEST;
    }

    @Override
    public boolean action(ServerSession session, ProtoMsg.Message message) {
        ProtoMsg.LoginRequest loginRequest = message.getLoginRequest();
        User user = User.fromMsg(loginRequest);
        long seqNo = message.getSequence();
        boolean isValidUser = checkUser(user);
        if (!isValidUser) {
            // 发送失败的报文
            ProtoInstant.ResultCodeEnum noToken = ProtoInstant.ResultCodeEnum.NO_TOKEN;
            ProtoMsg.Message response = loginResponceBuilder.loginResponse(noToken, seqNo, session.getSessionId());
            session.getChannel().writeAndFlush(response);
            return false;
        }

        // 发送成功的报文
        session.setUser(user);
        session.bind();

        ProtoInstant.ResultCodeEnum token = ProtoInstant.ResultCodeEnum.SUCCESS;
        ProtoMsg.Message response = loginResponceBuilder.loginResponse(token, seqNo, session.getSessionId());
        session.getChannel().writeAndFlush(response);

        return true;
    }

    private boolean checkUser(User user) {
        if (SessionMap.inst().hasLogin(user)) {
            LOGGER.error("用户已经登录");
            return false;
        }
        return true;
    }
}
